<?php
/**
 * Created by PhpStorm.
 * User: 毛文科
 * Date: 2019/5/22
 * Time: 18:17
 */
namespace app\admin\controller;
use app\admin\model\DataBases;
use app\admin\model\Models;
use app\admin\model\Subject;
use think\Controller;
use think\Request;
use app\admin\model\Fields as NewFields;

class Fields extends Controller{
    /**加载表格
     * @param Request $request
     * @return mixed
     */
    public function show_list(Request $request){
        $id = $request->param('id');
        $obj = new Subject();
        $obj->setModelId($id);
        return NewBuilder::make('table')
            ->addTableHeaderAllDel('fields/del?model_id='.$id)
            ->addTableHeaderAdd('fields/show_add?model_id='.$id)
            ->addTableHeaderBack('model/show_list')
            ->addTableHeaderText($obj->getModel()['model_table'])
            ->addTableColumn('id','text','ID')
            ->addTableColumn('field_name','text','字段中文名')
            ->addTableColumn('field','text','标识')
            ->addTableColumn('type','text','类型')
            ->addTableColumn('option','text','选项')
            ->addTableColumn('table','text','联表名称')
            ->addTableColumn('form_type','text','字段类型')
            ->addTableColumn('sort','text','排序')
            ->addTableColumn('defaults','text','默认值')
//            ->addTableColumn('status','switch','状态',['开启','禁用'],'fields/change')
            ->addTableColumn('delete','status','是否可删除',['可','不可'])
            ->addTableRightHeader('操作')
            ->addTableRight('edit','fields/show_edit?model_id='.$id,'修改')
            ->addTableRight('del','fields/del?model_id='.$id,'删除')
            ->addTablePage('fields/page?model_id='.$id,null,null,false)
            ->fetch();
    }

    /**加载数据
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function page(Request $request){
        $limit = $request->param('limit');
        $modelid = $request->param('model_id');
        $data = \app\admin\model\Fields::where('model_id',$modelid)
            ->order('sort desc,id asc')
            ->select()->toArray();
        $res['total'] = count($data);
        $res['data'] = $data;
        return json_page_response($res);
    }

    /**修改状态
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function change(Request $request){
        $id = $request->param('id');
        $data = \app\admin\model\Fields::where('id',$id)->findOrEmpty()->toArray();
        if($data['status']==1){
            $data['status'] = 0;
        }else{
            $data['status'] = 1;
        }
        if(\app\admin\model\Fields::update([
            'id'=>$data['id'],
            'status'=>$data['status']
        ])){
            return json_my_response('修改成功',200);
        }else{
            return json_my_response('修改失败');
        }
    }

    /**加载添加字段
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function show_add(Request $request){
        $model_id = $request->param('model_id');
        $array = [];
        $lianbiao = Models::where('model_type','联表模型')->select()->toArray();
        $array[''] = '无';
        foreach ($lianbiao as $value){
            $array[$value['model_table']] = $value['model_name'];
        }
        return NewBuilder::make('form')
            ->addText('提示','你好,请不要填写字段标识为aid,id,cid,name,pid,sort,tubiao,create_time,update_time,delete,status,delete_time,dir')
            ->addAction("fields/add")
            ->addNone('model_id',$model_id)
            ->addInput('field_name','字段中文名')
            ->addInput('field','标识')
            ->addSelect('type','类型',null,['varchar','int','text','float'])
            ->addInput('lang','长度',255)
            ->addInput('defaults','默认值','')
            ->addInput('option','选项(多个以英文,分隔)')
            ->addInput('sort','排序',100)
            ->addInput('hierarchy','联动下拉框层级(<=3)',1)
            ->addSelect('table','联动表名(联表模型可选择)',null,$array,true)
            ->addSelect('form_type','字段类型',null,['单行文本','多行文本','单文件','多文件','单图片','多图片','下拉框','联动下拉框','单选框','多选框','编辑框','开关','时间'])
            ->addSwitch('delete','是否可删除',0)
            ->addFormButton('submit','提交')
            ->addFormButton('back','返回')
            ->fetch();
    }

    /**添加字段
     * @param Request $request
     * @return \think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add(Request $request){
        $data = $request->param();
        $obj = new DataBases();
        if($obj->addFields($data)){
            if($data['option']){
                $data['option'] = trim($data['option'],',');
            }
            $data['status'] = 1;
            if(isset($data['delete'])&&$data['delete']=='on'){
                $data['delete'] = 1;
            }else{
                $data['delete'] = 0;
            }
            \app\admin\model\Fields::create($data);
            return redirect('index/errors',['code'=>200]);
        }else{
            return redirect('index/errors',['code'=>205]);
        }
    }

    /**加载修改字段
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function show_edit(Request $request){
        $id = $request->param('id');
        $model_id = $request->param('model_id');
        $array = [];
        $lianbiao = Models::where('model_type','联表模型')->select()->toArray();
        $array[''] = '无';
        foreach ($lianbiao as $value){
            $array[$value['model_table']] = $value['model_name'];
        }
        $data = NewFields::where('id',$id)->findOrEmpty()->toArray();
        return NewBuilder::make('form')
//            ->addText('提示','你好,请不要填写字段标识为aid,id,cid,name,pid,sort,tubiao,create_time,update_time,delete,status,delete_time,dir')
            ->addAction("fields/edit")
            ->addNone('model_id',$model_id)
            ->addNone('id',$id)
            ->addInput('field_name','字段中文名',$data['field_name'])
//            ->addInput('field','标识',$data['field'])
            ->addSelect('type','类型',$data['type'],['varchar','int','text','float'])
            ->addInput('lang','长度',$data['lang'])
            ->addInput('defaults','默认值',$data['defaults'])
            ->addInput('option','选项(多个以英文,分隔)',$data['option'])
            ->addInput('sort','排序',$data['sort'])
            ->addInput('hierarchy','联动下拉框层级(<=3)',$data['hierarchy'])
            ->addSelect('table','联动表名(联表模型可选择)',$data['table'],$array,true)
            ->addSelect('form_type','字段类型',$data['form_type'],['单行文本','多行文本','单文件','多文件','单图片','多图片','下拉框','联动下拉框','单选框','多选框','编辑框','开关','时间'])
            ->addSwitch('delete','是否可删除',$data['delete'])
            ->addFormButton('submit','提交')
            ->addFormButton('back','返回')
            ->fetch();
    }
    public function edit(Request $request){
        $data = $request->param();
        if($data['option']){
            $data['option'] = trim($data['option'],',');
        }
        if(isset($data['delete'])&&$data['delete']=='on'){
            $data['delete'] = 1;
        }else{
            $data['delete'] = 0;
        }
        $jiu = NewFields::where('id',$data['id'])->findOrEmpty()->toArray();
//        echo '<pre>';
//        print_r($data);
//        print_r($jiu);
//        exit;
        $bool = true;
        if($jiu){
            if($jiu['type']!==$data['type']||(int)$jiu['lang']!==(int)$data['lang']){
//                echo 1;exit;
                $obj = new DataBases();
                $bool = $obj->changeField($data);
            }
        }
//        echo 2;exit;
        if($bool){
            if(NewFields::where('id',$data['id'])->update($data)){
                return redirect('index/errors',['code'=>200]);
            }else{
                return redirect('index/errors',['code'=>205]);
            }
        }else{
            return redirect('index/errors',['code'=>205]);
        }
    }

    /**删除字段
     * @param Request $request
     * @return \think\response\Json
     */
    public function del(Request $request){
        $id = $request->param('id');
        $obj = new DataBases();
        if(!Subject::inspectDelete($id,false,session('modular').'_'.'fields')){
            return json_my_response('有不可删除的数据');
        }
        if(is_array($id)){
            foreach ($id as $value){
                if(!$obj->delField($value)){
                    return json_my_response('删除失败');
                }
            }
        }else{
            if(!$obj->delField($id)){
                return json_my_response('删除失败');
            }
        }
        if(NewFields::where('id','in',$id)->delete(true)){
            return json_my_response('删除成功',200);
        }else{
            return json_my_response('删除失败');
        }
    }
}